package com.restaurant.web;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.restaurant.domain.Menucategory;
import com.restaurant.service.MenucategoryService;
import com.restaurant.validators.MenuCategoryDeleteValidator;
import com.restaurant.validators.MenuCategoryValidator;

@Component
@RequestMapping("/action/menucategory.do")
@SessionAttributes("menucategory")
public class MenuCategoryFormController {
	
	@Autowired
	private MenuCategoryValidator menuCategoryValidator;
	@Autowired
	private MenuCategoryDeleteValidator menuCategoryDeleteValidator;
	@Autowired
	private MenucategoryService objMenucategoryService;
		
	@RequestMapping(method=RequestMethod.GET)
	public String menuCategory(ModelMap map, HttpServletRequest request, HttpServletResponse response){
		
		Menucategory menucategory = new Menucategory();		

		ArrayList<Menucategory> listMenucategories;//
		
		try {
			listMenucategories = (ArrayList<Menucategory>)objMenucategoryService.loadByHql("from Menucategory where isdeleted = false");
		} catch (Exception e) {
			listMenucategories = new ArrayList<Menucategory>();
		}
		
		map.addAttribute("menucategory", menucategory);		
		map.addAttribute("listMenucategories", listMenucategories);
		
		return "MenuCategory";
	}
	
	@RequestMapping(method=RequestMethod.POST)
	public String saveMenuCatetory(ModelMap map, @ModelAttribute ArrayList<Menucategory> listMenucategories, @ModelAttribute Menucategory menucategory, BindingResult result, HttpServletRequest request, HttpServletResponse response){
		
		String action = request.getParameter("action");
		
		 
		
		/***
		 * Called when a Add New request is called
		 * Comes form the hidden fields for form Tag
		 */
		if(action.equals("addnew")){
			menuCategoryValidator.validate(menucategory, result);
			if(result.hasErrors()){
				try {
					listMenucategories = (ArrayList<Menucategory>)objMenucategoryService.loadByHql("from Menucategory where isdeleted = false");
				} catch (Exception e) {
					listMenucategories = new ArrayList<Menucategory>();
				}
				map.addAttribute("listMenucategories", listMenucategories);
				return "MenuCategory";
			}
			
			if(menucategory.getFileData().getSize()>0){
				String imageUUID = UUID.randomUUID() + menucategory.getFileData().getOriginalFilename().substring(menucategory.getFileData().getOriginalFilename().lastIndexOf("."));
				menucategory.setImagepath(imageUUID);
				uploadFile(menucategory.getFileData(), request, imageUUID);
			}
			
			if(menucategory.getFileDataIcon().getSize()>0){
				String imageUUID = UUID.randomUUID() + menucategory.getFileDataIcon().getOriginalFilename().substring(menucategory.getFileDataIcon().getOriginalFilename().lastIndexOf("."));
				menucategory.setIconpath(imageUUID);
				uploadFile(menucategory.getFileDataIcon(), request, imageUUID);
			}
			
			menucategory.setIsdeleted(false);
			try {
				objMenucategoryService.addOrModify(menucategory);
			} catch (Exception e) {
				return "redirect:menucategory.do";
			}
			menucategory = new Menucategory();
		}
		
		/***
		 * Called when a edit request is called
		 * Comes form the hidden fields for form Tag
		 */
		
		else if(action.equals("edit")){
			Long menuCategoryID = null;
			try {
				menuCategoryID = Long.parseLong(request.getParameter("id"));
				menucategory = objMenucategoryService.loadByPrimaryKey(menuCategoryID);
			} catch (Exception e) {
				return "redirect:menucategory.do";
			}
		}
		
		/***
		 * Called when a edit request is called
		 * Comes form the hidden fields for form Tag
		 */
		else if(action.equals("del")){
			Long menuCategoryID = null;
			try {
				menuCategoryID = Long.parseLong(request.getParameter("id"));
				menucategory = objMenucategoryService.loadByPrimaryKey(menuCategoryID);
				menuCategoryDeleteValidator.validate(menucategory, result);
				if(result.hasErrors()){
					try {
						listMenucategories = (ArrayList<Menucategory>)objMenucategoryService.loadByHql("from Menucategory where isdeleted = false");
					} catch (Exception e) {
						listMenucategories = new ArrayList<Menucategory>();
					}
					map.addAttribute("listMenucategories", listMenucategories);
					return "MenuCategory";
				}
				menucategory.setIsdeleted(true);
				menucategory = objMenucategoryService.addOrModify(menucategory);
				menucategory = new Menucategory();
			} catch (Exception e) {
				menucategory = new Menucategory();
				return "redirect:menucategory.do";
			}			
		}
		
		else{
			return "redirect:menucategory.do";
		}
		
		
		
		try {
			listMenucategories = (ArrayList<Menucategory>)objMenucategoryService.loadByHql("from Menucategory where isdeleted = false");
		} catch (Exception e) {
			e.printStackTrace();
		}
		map.addAttribute("menucategory", menucategory);		
		map.addAttribute("listMenucategories", listMenucategories);		
		return "MenuCategory";			
	}
	
	private void uploadFile(MultipartFile file, HttpServletRequest request, String imagePath){
		try{
		String fileName = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        if (file.getSize() > 0) {
                inputStream = file.getInputStream();
                if (file.getSize() > 10000) {
//                        System.out.println("File Size:::" + file.getSize());
//                        return "/uploadfile";
                }
                
                fileName = request.getServletContext().getInitParameter("imagePath") + imagePath;
                outputStream = new FileOutputStream(fileName);
                int readBytes = 0;
                byte[] buffer = new byte[10000];
                while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
                        outputStream.write(buffer, 0, readBytes);
                }
                outputStream.close();
                inputStream.close();
        }
		}catch(IOException ex){
			ex.printStackTrace();
		}

	}	
	
}
